<template>
  <div class="page" v-loading="loading">
    <el-form :model="agentInfo" size="small" label-width="200px">
      <el-form-item label="Agent头像">
        <div class="uploaddiv" v-loading="uploadLoading">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="uploadHeaders"
          >
            <img
              v-if="agentInfo.header"
              :src="agentInfo.header"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="Agent名字">
        <el-input
          class="input1"
          v-model="agentInfo.name"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="Agent描述">
        <el-input
          class="input2"
          v-model="agentInfo.desc"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="请输入内容"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item label="mk中的应用名称">
        <el-autocomplete
          v-model="applicationForm.name"
          :fetch-suggestions="searchApplication"
          clearable
          placeholder="请输入应用名字"
          @select="handleSelectApplication"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="mk中的应用描述" v-if="applicationForm.name">
        <el-tag type="success">{{ applicationForm.desc }}</el-tag>
      </el-form-item>
      <el-form-item label="mk中的应用的AI模型" v-if="applicationForm.name">
        <el-tag type="success">{{ modelForm.name }}</el-tag>
      </el-form-item>
      <el-form-item label="mk中的应用的知识库" v-if="applicationForm.name">
        <el-tag type="success">{{ zskForm.name }}</el-tag>
      </el-form-item>
      <el-form-item label="单独设置个知识库" v-if="!applicationForm.name">
        <el-tag type="success">{{ agentInfo.zskName }}</el-tag>
        <el-button class="marginleft" size="mini" @click="clickChangeZSK()"
          >切换知识库</el-button
        >
      </el-form-item>
      <div v-if="!applicationForm.name">
        <el-form-item
          label="Agent使用的提示词名字"
          v-if="!applicationForm.name"
        >
          <el-select
            v-model="promptInfo.name"
            filterable
            placeholder="请选择"
            @change="changePrompt"
          >
            <el-option
              v-for="item in promptList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Agent使用的提示词性别">
          <span class="input1">
            {{ promptInfo.sex }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词风格">
          <span class="input1">
            {{ promptInfo.style }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词城市">
          <span class="input1">
            {{ promptInfo.city }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词职位">
          <span class="input1">
            {{ promptInfo.job }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词联系方式">
          <span class="input1">
            {{ promptInfo.phoneNumber }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词技能">
          <span class="input1">
            {{ promptInfo.skill }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词工作流">
          <span class="input1">
            {{ promptInfo.workflow }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词行业背景">
          <span class="input1">
            {{ promptInfo.industryBackground }}
          </span>
        </el-form-item>
        <el-form-item label="Agent使用的提示词模版">
          <el-input
            class="input2"
            v-model="promptInfo.prompt"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 40 }"
            placeholder="请输入内容"
            autocomplete="off"
            :disabled="true"
          ></el-input>
        </el-form-item>
      </div>
    </el-form>

    <el-button class="addmodel" size="small" type="primary" @click="clickSave"
      >保存</el-button
    >
    <!-- 切换知识库对话框 -->
    <el-dialog
      title="切换知识库"
      :visible.sync="zskDialog"
      width="35%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form :model="zskForm" size="small">
        <el-form-item label="知识库id">
          <el-autocomplete
            v-model="zskForm.name"
            :fetch-suggestions="searchZSK"
            clearable
            placeholder="请输入知识库名字"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="知识库名字">
          {{ zskForm.name }}
        </el-form-item>

        <el-form-item label="知识库描述">
          {{ zskForm.desc }}
        </el-form-item>
        <el-form-item label="关联应用数量">
          {{ zskForm.application_mapping_count }}
        </el-form-item>
        <el-form-item label="文档数量">
          {{ zskForm.document_count }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="zskDialog = false">取 消</el-button>
        <el-button type="primary" @click="clickConfirmChangeZSK"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { post } from "@/common/request";
import { toast } from "@/common/tools";
import { mapState } from "vuex";
export default {
  data() {
    return {
      // 提示词列表
      promptList: [],
      // 提示词模板
      promptInfo: {},
      // 搜索到的应用
      applicationForm: {},
      // 模型对象
      modelForm: {},
      // 搜索到的知识库的表单
      zskForm: {
        // 知识库的id
        id: "",
        // 知识库的名字
        name: "",
        // 知识库的描述
        desc: "",
        // 关联的应用数量
        application_mapping_count: 0,
        // 知识库的文档数量
        document_count: 0,
      },
      // 切换知识库对话框是否显示
      zskDialog: false,
      // 上传文件的loading
      uploadLoading: false,
      // 上传图片的headers
      uploadHeaders: {
        token: localStorage.getItem("ai_token"),
      },
      // 上传图片的url
      uploadUrl: "http://test.aiet.top:29004/front/search/uploadImage",
      // 切换模型对话框是否显示
      modelDialog: false,
      // 模型描述
      model_desc: "",
      // 模型名字
      model_name: "",
      // 应用id
      id: "",
      // 知识库id
      zskId: "",
      // 知识库名字
      zskName: "",
      loading: false,
      createDialog: false,
      editDialog: false,
      scanDialog: false,
      // 添加模型对话框是否显示
      dialogAddModel: false,
      // 添加模型的表单
      agentInfo: {
        id: 0,
        name: "",
        desc: "",
        // 知识库名字
        zskName: "",
        // 知识库id
        zskId: "",
        // 提示词id
        promptId: "",
        // 头像
        header: "",
      },
    };
  },
  created() {
    this.agentInfo.id = this.$route.query.id;
    this.list = [];
    this.getAgentInfo();
    this.getPromptList();
  },

  watch: {
    loginoutRandom() {
      this.reStart();
    },
  },

  computed: {
    ...mapState({
      userPackageInfo: (state) => state.userPackageInfo,
      loginoutRandom: (state) => state.loginoutRandom,
    }),
  },

  methods: {
    callback() {
      this.reStart();
    },

    reStart() {
      this.getAgentInfo();
      this.getPromptList();
    },

    // 获取agent详情
    getAgentInfo() {
      if (this.agentInfo.id !== "0") {
        console.log("获取到的agentid", this.agentInfo.id);
        this.$post("/front/tiyanAgent/byId", {
          id: this.agentInfo.id,
        })
          .then((res) => {
            console.log("获取agent详情", res.data.obj);
            if (res.data.code === 0) {
              this.agentInfo = res.data.obj;
              this.zskForm.id=this.agentInfo.zskId
              this.zskForm.name=this.agentInfo.zskName
              this.getPromptInfo();
              this.getPromptList();
              this.getApplicationInfo(this.agentInfo.applicationId);
            }
          })
          .catch(() => {
            console.log("应用详情获取失败");
          });
      } else {
      }
    },

    // 点击保存按钮
    clickSave() {
      // 选择了mk中的应用
      if (this.applicationForm.name) {
        this.agentInfo.applicationId = this.applicationForm.id;
        this.agentInfo.applicationName = this.applicationForm.name;
        this.agentInfo.promptId = '';
        this.agentInfo.promptName = '';
        this.agentInfo.zskId=this.zskForm.id
        this.agentInfo.zskName=this.zskForm.name
        
      } else if (this.promptInfo.name) {
        // 不使用知识库中的应用,使用自定义提示词+知识库
        this.agentInfo.promptId = this.promptInfo.id;
        this.agentInfo.promptName = this.promptInfo.name;
        this.agentInfo.applicationId = ''
        this.agentInfo.applicationName = ''
        this.agentInfo.zskId=this.zskForm.id
        this.agentInfo.zskName=this.zskForm.name
      } else {
        toast(1, "请选择提示词或者mk中的应用");
        return;
      }
      this.loading = true;
      console.log("点击保存按钮", this.agentInfo);
      if (this.agentInfo.id !== "0") {
        console.log("编辑agent");
        // 编辑体验agent
        this.$post("/front/tiyanAgent/update", this.agentInfo)
          .then((res) => {
            this.loading = false;
            if (res.data.code === 0) {
              toast(0, "更新成功");
              this.getAgentInfo();
            } else {
              toast(1, res.data.msg);
            }
          })
          .catch(() => {
            this.loading = false;
          });
        return;
      } else {
        console.log("创建agent");
        this.$post("/front/tiyanAgent/add", this.agentInfo)
          .then((res) => {
            console.log("创建agent成功", res.data);
            if (res.data.code === 0) {
              toast(0, "创建成功");
              this.loading = false;
              this.agentInfo = res.data.obj;
              this.getAgentInfo();
            } else {
              toast(1, "创建失败");
              this.loading = false;
            }
          })
          .catch(() => {
            console.log("应用详情获取失败");
            toast(1, "创建失败");
            this.loading = false;
          });
      }
    },
    // 点击切换模型
    clickQieHuanMoXing() {
      this.modelDialog = true;
    },
    // 获取提示词详情
    getPromptInfo() {
      if (this.agentInfo.promptId) {
        this.$post("/front/prompt/byId", {
          id: this.agentInfo.promptId,
        })
          .then((res) => {
            if (res.data.code === 0) {
              this.promptInfo = res.data.obj;
              console.log("提示词信息", this.promptInfo);
            }
          })
          .catch(() => {
            console.log("应用详情获取失败");
          });
      } else {
        console.log("应用详情获取失败");
      }
    },
    // 上传图片
    imgfileChange(e) {
      let file = e.target.files[0];
      let formData = new FormData();
      formData.append("file", file);
      if (this.isLoading) return;
      this.isLoading = true;
      post("/front/search/uploadImage", formData).then((res) => {
        this.isLoading = false;
        if (res.data.code === 0) {
          if (this.detail.url) this.detail.url += `,${res.data.obj}`;
          else this.detail.url = `${res.data.obj}`;
        } else {
          toast(1, "上传失败，请稍后重试");
        }
      });
      if (this.$refs.clearRef && this.$refs.clearRef.value)
        this.$refs.clearRef.value = ""; // 清空file文件
    },
    // 选择搜索出来的知识库
    handleSelect(item) {
      this.zskForm = item;
    },
    // 选择搜索出来的应用
    handleSelectApplication(item) {
      this.applicationForm = item;
      console.log("选择的应用", this.applicationForm);

      this.getApplicationInfo(this.applicationForm.id);
    },

    getApplicationInfo(id) {
      if (!id) {
        return;
      }
      this.$post("/front/dataset/getApplication", {
        id: id,
      })
        .then((res) => {
          if (res.data.code === 0) {
            this.applicationForm = res.data.obj;
            console.log("获取到的应用详情", this.applicationForm);
            this.getModelById(this.applicationForm.model);
            this.getZSKById(this.applicationForm.dataset_id_list[0]);
          }
        })
        .catch(() => {
          console.log("应用详情获取失败");
        });
    },
    // 通过id获取知识库详情
    getZSKById(id) {
      if (!id) {
        toast(1, "缺少知识库id");
      }
      // 获取提示词列表
      this.$post("/front/dataset/searchZSKById", {
        id: id,
      })
        .then((res) => {
          if (res.data.code === 0) {
            this.zskForm = res.data.obj;
          }
        })
        .catch(() => {
          toast(1, "获取提示词列表失败");
        });
    },
    // 点击确定切换模型
    clickConfirmChangeModel() {
      this.modelDialog = false;
      this.agentInfo.model_id = this.modelForm.id;
      this.clickSave();
    },
    handleAvatarSuccess(res, file) {
      console.log("上传成功", res.obj);
      this.uploadLoading = false;
      if (res.code === 0) {
        this.agentInfo.header = res.obj;
      } else {
        toast(1, "头像上传失败");
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/webp" ||
        file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 图片 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      const result = isJPG && isLt2M;
      if (result) {
        this.uploadLoading = true;
      }
      return result;
    },
    // 点击切换知识库
    clickChangeZSK(item) {
      this.zskDialog = true;
      console.log("点击切换知识库", this.weChatInfo);
    },
    // 获取提示词列表
    getPromptList() {
      this.$post("/front/prompt")
        .then((res) => {
          if (res.data.code === 0) {
            this.promptList = res.data.obj;
          }
        })
        .catch(() => {
          toast(1, "获取提示词列表失败");
        });
    },
    // 搜索知识库
    searchZSK(queryString, cb) {
      this.$post("/front/dataset/searchZSK", {
        name: queryString,
      }).then((res) => {
        if (res.data.code === 0) {
          if (res.data.obj.records) {
            const result = [];
            for (let i = 0; i < res.data.obj.records.length; i++) {
              result.push(res.data.obj.records[i]);
              result[i].value = res.data.obj.records[i].name;
            }
            cb(result);
            return;
          }
        }
      });
      cb([]);
    },
    // 切换提示词
    changePrompt(name) {
      console.log("切换提示词", name);

      const list = this.promptList.filter((item) => {
        return item.name === name;
      });
      this.promptInfo = { ...list[0] };
    },
    // 点击确定按钮,点击切换知识库对话框的确定按钮
    clickConfirmChangeZSK() {
      this.zskDialog = false;
      const data = {
        wechat: this.weChatInfo,
        zsk: this.zskForm,
      };
      this.agentInfo.zskName = this.zskForm.name;
      this.agentInfo.zskId = this.zskForm.id;
      console.log("data", this.agentInfo);

      // post("/front/dataset/changeZSK", data)
      //   .then((res) => {
      //     if (res.data.code === 0) {
      //       toast(0, "切换成功");
      //       this.getList();
      //     } else {
      //       toast(0, res.data.obj.msg);
      //     }
      //   })
      //   .catch(() => {
      //     toast(1, "切换失败");
      //   });
    },
    // 搜索应用
    searchApplication(queryString, cb) {
      this.$post("/front/dataset/searchZSKApplication", {
        name: queryString,
      }).then((res) => {
        if (res.data.code === 0) {
          if (res.data.obj && res.data.obj.records) {
            const result = [];
            for (let i = 0; i < res.data.obj.records.length; i++) {
              result.push(res.data.obj.records[i]);
              result[i].value = res.data.obj.records[i].name;
            }
            cb(result);
            return;
          }
        }
      });
      cb([]);
    },
    // 获取模型信息
    getModelById(modelId) {
      if (!modelId) {
        return;
      }
      this.$post("/front/dataset/getModel", {
        id: modelId,
      })
        .then((res2) => {
          if (res2.data.code === 0) {
            this.modelForm = res2.data.obj;
          }
        })
        .catch(() => {
          toast(1, "模型详情获取失败");
        });
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.el-icon-search:before) {
  color: #aaa !important;
}
:deep(.el-icon-circle-close) {
  font-size: 18px !important;
  color: #409eff !important;
}
.page {
  display: flex;
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  padding: 10px 10px 0;
}
.useridtitle {
  width: 50px;
  line-height: 40px;
  text-align: center;
  font-weight: 600;
}
.userid {
  width: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 13px;
  padding: 0 10px;
}
.wechatid {
  width: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 13px;
  padding: 0 10px;
}
.wechatnametitle {
  width: 180px;
  line-height: 40px;
  text-align: center;
  font-weight: 600;
}
.wechatstatustitle {
  width: 100px;
  line-height: 40px;
  text-align: center;
  font-weight: 600;
}
.wechatname {
  width: 180px;
  line-height: 50px;
  text-align: center;
  font-size: 13px;
  padding: 0 10px;
}
.zhishikid {
  margin: 10px 0;
}
:deep(.el-table) {
  overflow: scroll;
}
.el-table::-webkit-scrollbar {
  height: 10px;
  width: 10px;
}
.caozuo {
  display: flex;
  flex-direction: column;
  justify-content: start;
}
.addmodel {
  position: absolute;
  top: 90px;
  right: 40px;
}
.flex1 {
  display: flex;
  justify-content: space-between;
}
.tabs {
  height: 82vh;
}
.input1 {
  width: 400px;
}
.input2 {
  width: 900px;
}
.qiehuanmoxing {
  margin-left: 20px;
}

:deep(.el-button--primary) {
  span {
    color: #fff !important;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploaddiv {
  width: 180px;
  height: 180px;
}
.marginleft {
  margin-left: 10px;
}
</style>
